#include "header.h"
#include "debug.h"
#include "mtime.h"
#include "types.h"
#include "extern.h"

int set_mtrace (void){
	int gard;

		gard = setenv ("MALLOC_TRACE", "mtrace.out", 1);
		if (gard == 0)
			mtrace ();

	return gard;
}

void unset_mtrace (void){
	muntrace();
}

int InitDebugFiles (void)
{
	dfSys->fd = fopen (SYSFILE, "a");
	if (dfSys->fd == NULL){
		dfSys->fd = fopen (SYSFILE, "w");
			if (dfSys->fd == NULL){
				fprintf (stderr, "couldn't open sys debug file\n");
				return -1;
			}
	}

	dfMem->fd = fopen (MEMFILE, "a");
	if (dfMem->fd == NULL){
		dfMem->fd = fopen (MEMFILE, "w");
			if (dfMem->fd == NULL){
				fprintf (stderr, "couldn't open mem debug file\n");
				return -1;
			}
	}

 return 0;
}

int Debug (int label, const char* fmt, ...)
/*
	
*/
{
 time_t now;
 va_list ap;
 char msg[256];

	/*should use some getasciitime() function to replace "some time" [Done]*/

	va_start (ap, fmt);
	vsnprintf (msg, sizeof (msg), fmt, ap);
	va_end (ap);

	now = time (NULL); /* get the current time */

	if (now == -1){
		pthread_mutex_lock (&dfSys->mutex);
		fprintf (dfSys->fd, DEBUG_FATAL_FMT, "?", "clock error! <now = time (NULL)> failed\n");
		pthread_mutex_unlock (&dfSys->mutex);
		return -2; /*should represent a FATAL error*/
	}
	else
	{
		if ((label & DEBUG_SYS)&&(ServerConf.EnableSysDebug)){
			pthread_mutex_lock (&dfSys->mutex);
			switch (label){
				case DEBUG_INFO: fprintf (dfSys->fd, DEBUG_INFO_FMT, time_get_ascii(now), msg);
				case DEBUG_ERR: fprintf (dfSys->fd, DEBUG_ERR_FMT, time_get_ascii(now), msg);
				case DEBUG_FATAL: fprintf (dfSys->fd, DEBUG_FATAL_FMT, time_get_ascii(now), msg);
			}
			pthread_mutex_unlock (&dfSys->mutex);
		}
		else
		if ((label & DEBUG_MEM)&&(ServerConf.EnableMemDebug)){
			pthread_mutex_lock (&dfMem->mutex);
			switch (label){
				case DEBUG_INFO: fprintf (dfMem->fd, DEBUG_INFO_FMT, time_get_ascii(now), msg);
				case DEBUG_ERR: fprintf (dfMem->fd, DEBUG_ERR_FMT, time_get_ascii(now), msg);
				case DEBUG_FATAL: fprintf (dfMem->fd, DEBUG_FATAL_FMT, time_get_ascii(now), msg);
			}
			pthread_mutex_unlock (&dfMem->mutex);
		}

		if (label & DEBUG_STDOUT){
			switch (label){
				case DEBUG_INFO: fprintf (stdout, DEBUG_INFO_FMT, time_get_ascii(now), msg);
				case DEBUG_ERR: fprintf (stdout, DEBUG_ERR_FMT, time_get_ascii(now), msg);
				case DEBUG_FATAL: fprintf (stdout, DEBUG_FATAL_FMT, time_get_ascii(now), msg);
			}
		}
	}

 return 0;
}








